package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbUser;
import com.bwie.service.IProdService;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ProdEnum;
import com.bwie.vo.TbProdVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-03-21 14:06:58
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IUserService iUserService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    IProdService iProdService;

    @Override
    public R getOrderById(Integer orderId) {

        //-- 获取订单信息
        TbOrder tbOrder = tbOrderMapper.selectById(orderId);
        if(tbOrder == null) {
            return R.ERROR(404, "订单不存在");
        }

        //-- 获取用户信息:通过远程调用获取用户信息
//        String url = "http://localhost:9001/user/index/getUserById/" + tbOrder.getUserId();
//        R r = restTemplate.postForObject(url, null, R.class);
        R r = iUserService.getUserById(tbOrder.getUserId());
        if(r.getCode() != 200) {
            return r;
        }

        // 需要把R类里面的data转换为字符串，然后再把字符串转换为对象
        String data = JSON.toJSONString(r.getData());
        TbUser tbUser = JSON.parseObject(data, TbUser.class);

        tbOrder.setUser(tbUser);

        return R.OK(tbOrder);
    }

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {

        //-- 构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //-- 获取分页数据
        Page<TbOrder> list = tbOrderMapper.getOrderList(page);

        return R.OK(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProdVo> prodVoList) {

        //-- 获取消费者的ID
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        //-- 判断商品是否有效
        BigDecimal totalAmount = new BigDecimal(0.0);
        Integer totalNum = 0;
        for (TbProdVo tbProdVo : prodVoList) {
            if(tbProdVo.getProdStatus() != ProdEnum.ONLINE.getCode()) {
                return R.ERROR(500, "包含无效商品");
            }

            BigDecimal multiply = tbProdVo.getProdPrice().multiply(new BigDecimal(tbProdVo.getBuyNum()));

            totalAmount = totalAmount.add(multiply);

            totalNum += tbProdVo.getBuyNum();
        }

        //-- 判断库存/较少库存
        // 定义一个接口，统一扣减库存
        R r = iProdService.sucProdStock(prodVoList);
        if(r.getCode() != 200) {
            return R.ERROR(500, "库存不足");
        }

        //-- 生成订单
        TbOrder order = new TbOrder();
        order.setUserId(userId);
        // yyyyMMddHHmmss+4随机数

        String code = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        code += RandomUtil.randomNumbers(4);

        order.setOrderCode(code);
        order.setCreateTime(new Date());
        order.setOrderStatus(0);
        order.setOrderAmount(totalAmount);
        order.setProdCount(totalNum);

        tbOrderMapper.insert(order);

        //-- 生成订单明细
        for (TbProdVo tbProdVo : prodVoList) {
            TbOrderDetail detail = new TbOrderDetail();
            detail.setOrderId(order.getOrderId());
            detail.setProdId(tbProdVo.getProdId());
            detail.setProdPrice(tbProdVo.getProdPrice());
            detail.setProdNum(tbProdVo.getBuyNum());

            tbOrderDetailMapper.insert(detail);
        }

        return R.OK();
    }
}




